package com.zhoug.android.common.utils;

import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;

/**
 * 设备root检测
 * @Author 35574
 * @Date 2021/5/7
 * @Description
 */
public class RootCheckUtils {
    private static final String TAG = ">>>RootCheckUtils";

    /**
     * root检测
     * @return
     */
    public static boolean checkIsRoot() {
        long start = System.currentTimeMillis();
        if(checkRootPathSU()) {
            return true;
        }
        long end = System.currentTimeMillis();
        LogUtils.d(TAG, "checkIsRoot 耗时:"+(end-start));
        return false;
    }

    /**
     * 检测常用目录下是否存在su
     * 这个方法缺点是有可能漏掉一些不常用的目录。
     * @return
     */
    private static boolean checkRootPathSU() {
        File f = null;
        final String[] kSuSearchPaths = {"/system/bin/", "/system/xbin/", "/system/sbin/", "/sbin/", "/vendor/bin/"};
        try {
            for (int i = 0; i < kSuSearchPaths.length; i++) {
                f = new File(kSuSearchPaths[i] + "su");
                if (f.exists()) {
                    LogUtils.d(TAG, "find su in : "+kSuSearchPaths[i]);
                    if(canExecuteCommand(kSuSearchPaths[i]+"which su")) {
                        LogUtils.d(TAG, "execute whiec su in :"+kSuSearchPaths[i]);
                        return true;
                    }
                }
            }
            if(canExecuteCommand("busybox which su") || canExecuteCommand("which su")) {
                return true;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }

    /**
     * 检查是否可以执行cmd命令
     * @param command 命令
     * @return
     */
    private static boolean canExecuteCommand(String command) {
        if(command==null || !command.endsWith("which su")){
            return false;
        }
        Process process = null;
        BufferedReader in = null;
        String result = null;
        try {
            process = Runtime.getRuntime().exec(command);
            in = new BufferedReader(new InputStreamReader(process.getInputStream()));
            result = in.readLine();
        } catch (Exception e) {
            //do noting
            e.printStackTrace();
        } finally {
            if(in != null) {
                try {
                    in.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (process != null) {
                process.destroy();
            }
        }
        return (null != result);
    }



}
